package com.ymt.reliable.message.queue.activemq.service.impl;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;

@Configuration
@ConditionalOnProperty(prefix = "activeMq", name = "url", matchIfMissing = false)
public class ActiveMqConfig {
    @Value("${activeMq.url}")
    private String brokerURL;
    @Value("${activeMq.username:'admin'}")
    private String userName;
    @Value("${activeMq.password:'admin'}")
    private String password;

    @Bean(name = "activeMqConnectionFactory")
    public CachingConnectionFactory cachingConnectionFactory() {
        ActiveMQConnectionFactory targetConnectionFactory = new ActiveMQConnectionFactory();
        targetConnectionFactory.setBrokerURL(brokerURL);
        targetConnectionFactory.setUserName(userName);
        targetConnectionFactory.setPassword(password);

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setTargetConnectionFactory(targetConnectionFactory);
        connectionFactory.setSessionCacheSize(100);
        return connectionFactory;
    }

    @Bean
    public JmsTemplate jmsTemplate(CachingConnectionFactory connectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
        return jmsTemplate;
    }
}
